﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data.Core.Models;
using System.Data.Entity;
using Data.Core;

namespace Data.Service
{
    public class PostService : IPostService
    {
        public void Delete(Post post)
        {
            if (post == null)
            {
                throw new ArgumentNullException("post");
            }
            using (var db = new BloggingContext())
            {
                db.Set<Post>().Attach(post);
                db.Entry<Post>(post).State = EntityState.Deleted;
                db.SaveChanges();
            }
        }

        public IList<Post> GetPostsByBlogId(int blogId)
        {
            if (blogId == 0)
            {
                return null;
            }
            using (var db = new BloggingContext())
            {
                var posts = db.Posts.Where(c => c.BlogId == blogId).ToList();
                return posts;
            }
        }

        public void Insert(Post post)
        {
            if (post == null)
            {
                throw new ArgumentNullException("post");
            }
            using (var db = new BloggingContext())
            {
                db.Posts.Add(post);
                db.SaveChanges();
            }
        }

        public void Update(Post post)
        {
            if (post == null)
            {
                throw new ArgumentNullException("post");
            }
            using (var db = new BloggingContext())
            {
                db.Set<Post>().Attach(post);
                db.Entry<Post>(post).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
    }
}
